//引入VueRouter
import VueRouter from "vue-router";

//引入需要路由的组件
import Login from "@/views/login/Login.vue";
import Home from "@/views/home/Home.vue";
import HomeMain from "@/views/home/HomeMain";
import UserList from "@/views/user/UserList";
import QuestionList from "@/views/question/QuestionList";
import TestQuestion from "@/views/question/TestQuestion";
import QuestionCount from "@/views/questioncount/QuestionCount";
import MineInfo from "@/views/mine/MineInfo";
import store from "@/store";

//创建实例
const router = new VueRouter({
    routes:[
        //路由重定向
        {   path: '/', redirect: '/Login'   },
        {   path: "/Login", component: Login    },
        {   path: '/Home', component: Home,
            redirect: '/Home/HomeMain',
            children: [
                //二级路径不加'/'
                {   path: 'HomeMain',component: HomeMain,   },  //首页
                {   path: 'UserList',component: UserList,   },  //用户列表
                {   path: 'QuestionList',component: QuestionList,   },  //问卷列表
                {   path: 'TestQuestion',component: TestQuestion,   },  //试题管理
                {   path: 'QuestionCount',component: QuestionCount,   },//问卷统计
                {   path: 'MineInfo',component: MineInfo,   },  //我的
            ]
        },
    ]
})

/**
 * 声明全局的导航守卫（全局前置守卫）
 * 三个参数，to（到哪去）,from（从哪来）,next函数[next()表示放行,next("/login")强制跳转到指定页面,next(false)强制停留在当前页],
 */
router.beforeEach(function (to,from,next){
    console.log(to);
    if(to.path!='/Login'){
        const admin = localStorage.getItem('admin');
        // console.log(admin);
        if(admin){
            next();
        }else{
            store.commit('ChangeLoginStatus');
            alert('请先登录');
            next('/Login');
        }
    }else{
        next();
    }
})

export default router
